package com.aiyan.edu.service.order.task;

import com.aiyan.edu.framework.domain.task.Task;
import com.aiyan.edu.service.order.config.RabbitmqConfig;
import com.aiyan.edu.service.order.service.TaskService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

/**
 * 通知选课任务
 *
 * @author: zqzhou
 * @create: 2019/11/24 16:09
 **/
@Component
public class ChooseCourseTask {

    @Autowired
    TaskService taskService;

    @RabbitListener(queues = RabbitmqConfig.QUEUE_LEARNING_FINISHADDCHOOSECOURSE)
    public void finishChose(Task task) {
        if (task != null && StringUtils.isNotEmpty(task.getId())) {
            this.taskService.finishTask(task.getId());
        }
    }

    /**
     * 发送选课消息，通知选课
     */
    @Scheduled(cron = "0/10 * * * * *")
    public void noticeChoose() {
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(new Date());
        calendar.set(GregorianCalendar.MINUTE, -1);

        List<Task> taskList = this.taskService.findTaskList(calendar.getTime(), 10);

        if (CollectionUtils.isEmpty(taskList)) {
            return;
        }

        taskList.forEach(task -> {
            // 通过乐观锁的方式获取任务
            if (this.taskService.getTask(task.getId(), task.getVersion()) > 0) {
                this.taskService.publish(task);
            }
        });
    }
}
